<template>
  <div>
    <div class="flex items-center">
      <div class="total">共 {{ total }} 条</div>
      <div class="w-1px h-16px bg-[#ddd] mx-16px line"></div>
      <div class="flex items-center btnbox">
        <el-button @click="handleBatchRemark">批量备注</el-button>
        <el-button @click="handleChange">批量变更</el-button>
        <el-button @click="handleAudit">审核通过</el-button>
        <el-button @click="handleWaitConfirm">转为待确认</el-button>
        <el-button @click="handleInvalid">无效订单</el-button>
        <el-button @click="handleToUnsigned">变更未签收</el-button>
        <el-button @click="handleReturnGoods">退货 </el-button>
        <el-button @click="handleAbnormal">订单异常</el-button>
        <el-button @click="handleSends">发货</el-button>
        <el-button @click="handleCancel">取消订单</el-button>
      </div>
      <div class="w-1px h-16px bg-[#ddd] mx-16px line"></div>
      <div class="text-[#333] text-[14px] flex items-center time">
        <div class="mr-4px">下单时间</div>
        <div class="flex flex-col relative arrowbox" @click="handleSort">
          <Icon
            icon="ep:caret-top"
            :color="sort === 'DESC' ? '#999' : '#333'"
            :size="12"
            class="absolute bottom-[-1px] cursor-pointer"
          />
          <Icon
            icon="ep:caret-bottom"
            :color="sort === 'DESC' ? '#333' : '#999'"
            :size="12"
            class="absolute top-[-1px] cursor-pointer"
          />
        </div>
      </div>
    </div>
    <!-- 批量备注 -->
    <ComfirmPops
      ref="batchMarkRef"
      :type="'form'"
      :showIcon="false"
      :show-dot="false"
      :title="'批量备注'"
      @confirm="batchMark"
    >
      <template #content>
        <div class="flex py-10px cont">
          <div class="label mr-15px text-[13px] shrink-0">备注</div>
          <div class="w-full val">
            <el-input
              v-model="remark"
              resize="none"
              type="textarea"
              :rows="6"
              maxlength="200"
              :show-word-limit="true"
              placeholder="请输入备注"
              class="w-full"
            />
          </div>
        </div>
      </template>
    </ComfirmPops>
    <!-- 审核提示 -->
    <ComfirmPops ref="auditRef" type="tips" title="确定提示" @confirm="getAuditRes">
      <template #content>
        <div class="">确认要通过审核吗？</div>
      </template>
    </ComfirmPops>
    <!-- 审核提示 -->
    <ComfirmPops ref="returnGoodsRef" type="tips" title="确定提示" @confirm="getReturnGoodsRes">
      <template #content>
        <div class="">确认要退货吗？</div>
      </template>
    </ComfirmPops>
    <!-- 发货提示 -->
    <ComfirmPops ref="sendsRef" type="tips" title="确定提示" @confirm="getSendsRes">
      <template #content>
        <div class="">确认要发货吗？</div>
      </template>
    </ComfirmPops>
    <!-- 转为待确认提示 -->
    <ComfirmPops ref="waitComfirmRef" type="tips" title="确定提示" @confirm="getWaitComfirmRes">
      <template #content>
        <div class="">确认要转为待确认吗？</div>
      </template>
    </ComfirmPops>
    <!-- 转为未签收 -->
    <ComfirmPops ref="unsignedRef" type="tips" title="确定提示" @confirm="getUnsignedRes">
      <template #content>
        <div class="">确认要转为未签收吗？</div>
      </template>
    </ComfirmPops>
    <!-- 取消订单 -->
    <ComfirmPops
      ref="cancelRef"
      :show-icon="false"
      :show-dot="false"
      title="确认要取消订单吗？"
      :type="'radio'"
      @confirm="getCancelRes"
    >
      <template #content>
        <div class="text-[#999] text[14px] desc">
          取消订单后订单状态将变成无效订单，请选择订单取消后： 采购库存是否对应减少
        </div>
        <div class="mt-[15px] pb-[20px]">
          <el-radio-group text-color="#3721FF" v-model="cancelRadio">
            <el-radio :value="0">是，减少采购库存</el-radio>
            <el-radio :value="1">否，保留采购库存</el-radio>
          </el-radio-group>
        </div>
      </template>
    </ComfirmPops>
    <!-- 无效订单 -->
    <ComfirmPops
      ref="invalidRef"
      :show-icon="false"
      :show-dot="true"
      width="500px"
      :type="'radio'"
      @confirm="getInvalidRes"
    >
      <template #content>
        <div class="flex items-baseline">
          <div class="flex items-center shrink-0 mr-15px lable">
            <div class="txt">无效原因</div>
            <div class="red">*</div>
          </div>
          <div class="val">
            <el-checkbox-group v-model="reasonValue">
              <el-checkbox
                v-for="(item, index) in reasonList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-checkbox-group>
          </div>
        </div>
        <div class="flex mt-[10px] items-start">
          <div class="label mr-15px text-[13px] shrink-0">
            <div class="txt">备注原因</div>
            <div class="red"></div>
          </div>
          <div class="w-full val">
            <el-input
              v-model="remark"
              resize="none"
              type="textarea"
              :rows="6"
              maxlength="200"
              :show-word-limit="true"
              placeholder="请输入备注"
              class="w-full"
            />
          </div>
        </div>
      </template>
    </ComfirmPops>
    <!-- 异常订单 -->
    <ComfirmPops
      ref="abnormalRef"
      :show-icon="false"
      :show-dot="true"
      title="异常订单"
      width="600px"
      :type="'radio'"
      @confirm="getAbnormalRes"
    >
      <template #content>
        <div class="flex items-baseline">
          <div class="flex items-center shrink-0 mr-15px lable">
            <div class="txt">无效原因</div>
            <div class="red">*</div>
          </div>
          <div class="val">
            <el-checkbox-group v-model="reasonValue">
              <el-checkbox
                v-for="(item, index) in abnormalReasonList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-checkbox-group>
          </div>
        </div>
        <div class="flex mt-[10px] items-start">
          <div class="label mr-15px text-[13px] shrink-0">
            <div class="txt">备注原因</div>
            <div class="red"></div>
          </div>
          <div class="w-full val">
            <el-input
              v-model="remark"
              resize="none"
              type="textarea"
              :rows="6"
              maxlength="200"
              :show-word-limit="true"
              placeholder="请输入备注"
              class="w-full"
            />
          </div>
        </div>
        <div class="mt-[10px] flex">
          <div class="flex items-center shrink-0 mr-15px lable">
            <div class="txt">订单取消后，采购库存是否对应减少</div>
            <div class="red">*</div>
          </div>
          <div class="val">
            <el-radio-group text-color="#3721FF" v-model="cancelRadio">
              <el-radio :value="0">是，减少采购库存</el-radio>
              <el-radio :value="1">否，保留采购库存</el-radio>
            </el-radio-group>
          </div>
        </div>
      </template>
    </ComfirmPops>
  </div>
</template>

<script setup lang="ts">
import { ElLoading } from 'element-plus'
import * as TradeOrderApi from '@/api/mall/trade/order'

type SortType = 'DESC' | 'ASC'
const message = useMessage()
const emit = defineEmits(['updateList', 'updateSort'])
defineOptions({ name: 'BatchAction' })
const props = defineProps({
  total: {
    type: Number,
    default: 0
  },
  sort: {
    type: String as () => SortType,
    default: 'DESC'
  },
  selectedRows: {
    type: Array,
    default: () => []
  }
})

const actionName = ref('')

const loading = ref()

const batchMarkRef = ref()

const returnGoodsRef = ref()

const auditRef = ref()

const sendsRef = ref()

const waitComfirmRef = ref()

const unsignedRef = ref()

const cancelRef = ref()

const invalidRef = ref()

const abnormalRef = ref()

const remark = ref('')

const reasonValue = ref([])

const reasonList = [
  { label: '客户取消', value: 1 },
  { label: '重复下单', value: 2 },
  { label: '恶意下单', value: 3 },
  { label: '缺货', value: 4 },
  { label: '无效订单', value: 5 },
  { label: '订单黑名单', value: 6 },
  { label: '电话错误', value: 7 },
  { label: '未支付', value: 8 },
  { label: '其他', value: 9 }
]

const abnormalReasonList = [
  { label: '丢件', value: 1 },
  { label: '报关失败', value: 2 },
  { label: '破损', value: 3 },
  { label: '暂缓发货', value: 4 },
  { label: '订单超时', value: 5 },
  { label: '其他', value: 6 }
]

const cancelRadio = ref(0)

const dataInit = () => {
  remark.value = ''
  reasonValue.value = []
  cancelRadio.value = 0
}

/**
 * 批量备注
 */
const batchMark = async () => {
  if (!remark.value) {
    message.error('请输入备注')
    return
  }

  loading.value = ElLoading.service({
    lock: true,
    text: '处理中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  // 执行接口
  try {
    const orderNo = props.selectedRows.map((item) => item.orderNo)
    await TradeOrderApi.updateOrderRemarkNew({ orderNo: orderNo, remark: remark.value })
    message.success('操作成功')
    emit('updateList')
    dataInit()
  } catch (error) {
    message.error(error.msg)
  } finally {
    batchMarkRef.value.hide()
    loading.value.close()
  }
}
/*
 * 批量备注显示
 */
const handleBatchRemark = () => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  batchMarkRef.value.show()
}
/**
 * 审核
 */
const getAuditRes = async (res: boolean) => {
  if (res) {
    loading.value = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    // 执行接口
    try {
      const orderNo = props.selectedRows.map((item) => item.orderNo)
      await TradeOrderApi.approvedOrder({ orderNo: orderNo })
      message.success('操作成功')
      emit('updateList')
      dataInit()
    } catch (error) {
      message.error(error.msg)
    } finally {
      auditRef.value.hide()
      loading.value.close()
    }
  }
}
/*
 * 审核显示
 */
const handleAudit = () => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  auditRef.value.show()
}

/**
 * 确认发货
 */
const getSendsRes = async (res: boolean) => {
  if (res) {
    loading.value = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    // 执行接口

    // sendsRef.value.hide()
    // loading.value.close()
    // message.success('操作成功')
    // emit('updateList')
    try {
      const orderNo = props.selectedRows.map((item) => item.orderNo)
      await TradeOrderApi.updateOrderStatus({
        orderNo: orderNo,
        status: 5
      })
      message.success('操作成功')
      emit('updateList')
      dataInit()
    } catch (error) {
      message.error(error.msg)
    } finally {
      sendsRef.value.hide()
      loading.value.close()
    }
  }
}

/**
 * 发货
 */
const handleSends = () => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  sendsRef.value.show()
}

/**
 * 确认转待确认
 */
const getWaitComfirmRes = async (res: boolean) => {
  if (res) {
    loading.value = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    // 执行接口
    try {
      const orderNo = props.selectedRows.map((item) => item.orderNo)
      await TradeOrderApi.updateOrderStatus({ orderNo: orderNo, status: 2 })
      message.success('操作成功')
      emit('updateList')
      dataInit()
    } catch (error) {
      message.error(error.msg)
    } finally {
      waitComfirmRef.value.hide()
      loading.value.close()
    }
  }
}

/**
 * 待确认
 */
const handleWaitConfirm = () => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  waitComfirmRef.value.show()
}

/**
 * 取消订单
 */
const handleCancel = () => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  cancelRef.value.show()
}

/**
 * 确认取消订单
 */
const getCancelRes = async () => {
  loading.value = ElLoading.service({
    lock: true,
    text: '处理中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  // 执行接口
  // cancelRef.value.hide()
  // loading.value.close()
  // message.success('操作成功')
  // emit('updateList')

  try {
    const orderNo = props.selectedRows.map((item) => item.orderNo)
    await TradeOrderApi.updateOrderStatus({
      orderNo: orderNo,
      status: 9,
      inventoryFlag: cancelRadio.value ? true : false
    })
    message.success('操作成功')
    emit('updateList')
    dataInit()
  } catch (error) {
    message.error(error.msg)
  } finally {
    cancelRef.value.hide()
    loading.value.close()
  }
}

/**
 * 确认转为未签收
 */
const handleToUnsigned = () => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  unsignedRef.value.show()
}

/**
 * 确认转为未签收
 */
const getUnsignedRes = async (res: boolean) => {
  if (res) {
    loading.value = ElLoading.service({
      lock: true,
      text: '处理中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    // 执行接口
    // unsignedRef.value.hide()
    // loading.value.close()
    // message.success('操作成功')
    // emit('updateList')
    try {
      const orderNo = props.selectedRows.map((item) => item.orderNo)
      await TradeOrderApi.updateOrderStatus({
        orderNo: orderNo,
        status: 7
      })
      message.success('操作成功')
      emit('updateList')
      dataInit()
    } catch (error) {
      message.error(error.msg)
    } finally {
      unsignedRef.value.hide()
      loading.value.close()
    }
  }
}

const handleInvalid = () => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  invalidRef.value.show()
}

/**
 * 确认转为无效订单
 */
const getInvalidRes = async () => {
  if (!reasonValue.value.length) {
    message.error('请选择无效原因')
    return
  }
  loading.value = ElLoading.service({
    lock: true,
    text: '处理中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  // // 执行接口
  // invalidRef.value.hide()
  // loading.value.close()
  // message.success('操作成功')
  // emit('updateList')
  try {
    const orderNo = props.selectedRows.map((item) => item.orderNo)
    await TradeOrderApi.updateOrderStatus({
      orderNo: orderNo,
      invalidReason: reasonValue.value.join(','),
      remark: remark.value,
      status: 9
    })
    message.success('操作成功')
    emit('updateList')
    dataInit()
  } catch (error) {
    message.error(error.msg)
  } finally {
    invalidRef.value.hide()
    loading.value.close()
  }
}

const handleAbnormal = () => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  abnormalRef.value.show()
}

/**
 * 确认转为异常订单
 */
const getAbnormalRes = async () => {
  if (!reasonValue.value.length) {
    message.error('请选择异常原因')
    return
  }
  loading.value = ElLoading.service({
    lock: true,
    text: '处理中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  // 执行接口
  // abnormalRef.value.hide()
  // loading.value.close()
  // message.success('操作成功')
  // emit('updateList')
  try {
    const orderNo = props.selectedRows.map((item) => item.orderNo)
    await TradeOrderApi.updateOrderStatus({
      orderNo: orderNo,
      invalidReason: reasonValue.value.join(','),
      remark: remark.value,
      inventoryFlag: cancelRadio.value ? true : false,
      status: 8
    })
    message.success('操作成功')
    emit('updateList')
    dataInit()
  } catch (error) {
    message.error(error.msg)
  } finally {
    abnormalRef.value.hide()
    loading.value.close()
  }
}

/**
 * 退货
 */
const handleReturnGoods = () => {
  if (!props.selectedRows.length) {
    message.error('请选择订单')
    return
  }
  returnGoodsRef.value.show()
}

/**
 * 确认退货
 */
const getReturnGoodsRes = async () => {
  // if (!reasonValue.value.length) {
  //   message.error('请选择退货原因')
  //   return
  // }
  loading.value = ElLoading.service({
    lock: true,
    text: '处理中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  // 执行接口
  // returnGoodsRef.value.hide()
  // loading.value.close()
  // message.success('操作成功')
  // emit('updateList')
  try {
    const orderNo = props.selectedRows.map((item) => item.orderNo)
    await TradeOrderApi.updateOrderStatus({
      orderNo: orderNo,
      status: 10
    })
    message.success('操作成功')
    emit('updateList')
    dataInit()
  } catch (error) {
    message.error(error.msg)
  } finally {
    returnGoodsRef.value.hide()
    loading.value.close()
  }
}

const handleChange = () => {
  message.warning('该功能暂未开放')
}

const handleSort = () => {
  emit('updateSort', props.sort === 'DESC' ? 'ASC' : 'DESC')
}
</script>

<style lang="scss" scoped>
:deep(.el-button) {
  border-radius: 10px;
}
</style>
